/**
 * 密钥协商
 * @param target 目标的参数对象
 * @param userId 需要保存的用户id，用于标识共享密钥的所有人
 * @returns 密钥协商状态
 */
export const keyNegotiation = async (
  target: {
    dhPublicKey: string;
    rsaPublicKey: string;
    sign: string;
  },
  userId
): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    window.electron.ipcRenderer.send(
      'key-negotiation',
      target.dhPublicKey,
      target.rsaPublicKey,
      target.sign,
      userId
    );
    window.electron.ipcRenderer.once('key-negotiation', (_, status) => {
      if (status) {
        resolve(true);
      } else {
        reject(false);
      }
    });
  });
};

/**
 * aes加密
 * @param friendId 好友id
 * @param message 加密消息
 * @returns 加密后的消息
 */
export const aesEncrypt = (
  friendId: string,
  message: string
): Promise<{
  iv: string;
  encrypted: string;
}> => {
  return new Promise((resolve, reject) => {
    window.electron.ipcRenderer.send('aes-encrypt', friendId, message);
    window.electron.ipcRenderer.once(
      'aes-encrypt',
      (
        _event,
        data: {
          iv: string;
          encrypted: string;
        }
      ) => {
        if (!data) {
          reject('加密失败');
        }
        resolve(data);
      }
    );
  });
};

/**
 * aes解密
 * @param encrypted 加密后的消息
 * @param iv 偏移量
 * @returns 解密后的消息
 */
export const aesDecrypt = (
  senderId: string,
  iv: string,
  encrypted: string
): Promise<string> => {
  return new Promise((resolve, reject) => {
    window.electron.ipcRenderer.send('aes-decrypt', senderId, iv, encrypted);
    window.electron.ipcRenderer.once('aes-decrypt', (_event, data) => {
      console.log('aes解密的明文：', data);
      if (data in Error) {
        reject(data);
      }
      resolve(data);
    });
  });
};
